﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
//using System.Collections;
using System.Xml;
using System.Web.Services;

public partial class Finance_ProfitClear : ATPages
{
    Function f = new Function();
    ZSql zs = new ZSql();
    protected void Page_Load(object sender, EventArgs e)
    {
        lblPath.Text = f.getModuleidAdd(Request.QueryString["moduid"].ToString());
        hfxs.Value = Request.QueryString["moduid"].ToString();
        if (!IsPostBack)
        {
            HidWareid.Value = getWareId();
            initKdate();
            initData();
            inDepartment();
            txtKdate.Text = Request.QueryString["Kdate"];
            txtJdate.Text = Request.QueryString["Jdate"];
            SalesCode.Text = Request.QueryString["SalesCode"];
            GuestName.Text = Request.QueryString["GuestName"];
            TypeName.Text = Request.QueryString["TypeName"];
            brand.Text = Request.QueryString["brand"];
            ddltypeSale.SelectedValue = Request.QueryString["typeSale"];
            ddrDepartment.SelectedValue = Request.QueryString["deptid"];
            ComoditiesName.Text = Request.QueryString["comodName"];
        }
    }


    private void inDepartment()
    {
        ZSql Dep = new ZSql();
        Dep.Open("select * from Department");
        ddrDepartment.DataSource = Dep.m_table;
        ddrDepartment.DataTextField = "Deptname";
        ddrDepartment.DataValueField = "Deptid";
        ddrDepartment.DataBind();
        ddrDepartment.Items.Insert(0, new ListItem("所有部门", ""));
        Dep.Close();
    }

    private void initData()
    {
        string search = "";
        string countSql = "";
        string sql = "select * , (TotalPractical - SuppliMoney * number) AS Profit from (select a.*, (SELECT ComoditiesType  FROM ComoditiesType  WHERE TypeId = isnull ((SELECT TOP 1 TypeId FROM Specifications WHERE a.ComodBarcode = modulbh), 0)) AS TypeName,(SELECT TOP 1 SuppliMoney FROM CS_Stock  WHERE a.ComodBarcode = ComodBarcode  ORDER BY StockId DESC) AS SuppliMoney,(select top 1 realname from UserInfo where a.userid=userid) as realname, (select GuestName from CS_Guest where a.guestid=guestid) as GuestName,(select Address from CS_Guest where a.guestid=guestid) as Address,(select Phone from CS_Guest where a.guestid=guestid) as Phone,(select StaffName from CS_Staff where StaffId=a.Saleman) as  StaffName,(select deptName from department where a.deptid=deptid) as deptName  from CS_Sales a )TblSales where 1=1 and isDel=0";

        if (!string.IsNullOrEmpty(Request.QueryString["Kdate"]) && !string.IsNullOrEmpty(Request.QueryString["Jdate"]))//时间起止
        {
            search += "&Kdate=" + Request.QueryString["Kdate"].Trim();
            search += "&Jdate=" + Request.QueryString["Jdate"].Trim();
            sql += " and c_date>='" + Request.QueryString["Kdate"] + "' and c_date<='" + Request.QueryString["Jdate"] + "' ";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["SalesCode"]))//订单号
        {
            search += "&SalesCode=" + Request.QueryString["SalesCode"].Trim();
            sql += " and SalesCode like '%" + Request.QueryString["SalesCode"].Trim() + "%'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["GuestName"]))//客户名称
        {
            search += "&GuestName=" + Request.QueryString["GuestName"].Trim();
            sql += " and GuestName like '%" + Request.QueryString["GuestName"].Trim() + "%'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["comodName"]))//商品名称
        {
            search += "&comodName=" + Request.QueryString["comodName"].Trim();
            sql += " and comodName like '%" + Request.QueryString["comodName"].Trim() + "%'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["TypeName"]))//型号编号
        {
            search += "&TypeName=" + Request.QueryString["TypeName"].Trim();
            sql += " and TypeName='" + Request.QueryString["TypeName"].Trim() + "'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["brand"]))//型号编号
        {
            search += "&brand=" + Request.QueryString["brand"].Trim();
            sql += " and brand='" + Request.QueryString["brand"].Trim() + "'";
        }
        if (!string.IsNullOrEmpty(Request.QueryString["typeSale"]))//销售类型
        {
            search += "&typeSale=" + Request.QueryString["typeSale"].Trim();
            sql += " and typeSale=" + Request.QueryString["typeSale"].Trim();
        }
        if (!string.IsNullOrEmpty(Request.QueryString["deptid"]))//部门
        {
            search += "&deptid=" + Request.QueryString["deptid"].Trim();
            sql += " and deptid=" + Request.QueryString["deptid"].Trim();
        }
        //统计countSql：countSaleNum，CountSaleMoney
        countSql = "select isnull(sum(number),0) as countSaleNum,isnull(sum(Totalpractical),0) as CountSaleMoney,isnull(sum(Profit),0) as countProfit from(" + sql + ") DERIVEDTBL";
        sql += " order by SalesId desc";

        PageNavigator1.Url = "../Finance/ProfitClear.aspx?moduid=" + hfxs.Value + search;
        PageNavigator1.Total = 1;
        PageNavigator1.Query = sql;


        //Response.Write(countSql);
        //Response.End();
        //读取统计数据
        zs.Open(countSql);
        if (zs.m_table.Rows.Count > 0)
        {
            countSaleNum.Text = zs.m_table.Rows[0]["countSaleNum"].ToString();
            countSaleMoney.Text = Convert.ToInt32(zs.m_table.Rows[0]["countSaleMoney"]).ToString();
            countProfit.Text = Convert.ToInt32(zs.m_table.Rows[0]["countProfit"]).ToString();
            
        }
        zs.Close();

    }
    private string getWareId()
    {
        ZSql zs = new ZSql();
        string sql = "select WarehouseId from UserInfo where userid=" + Request.Cookies["user"].Values["id"];
        zs.Open(sql);

        zs.Close();
        return zs.m_table.Rows[0]["WarehouseId"].ToString();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string search = "";
        if (!string.IsNullOrEmpty(txtKdate.Text) && !string.IsNullOrEmpty(txtJdate.Text.Trim()))//时间起止
        {
            search += "&Kdate=" + txtKdate.Text.Trim();
            search += "&Jdate=" + txtJdate.Text.Trim();
        }
        if (!string.IsNullOrEmpty(SalesCode.Text.Trim()))//订单号
        {
            search += "&SalesCode=" + Common.FormatParameter(SalesCode.Text.Trim());
        }
        if (!string.IsNullOrEmpty(GuestName.Text.Trim()))//客户名称
        {
            search += "&GuestName=" + Common.FormatParameter(GuestName.Text).Trim();
        }
        if (!string.IsNullOrEmpty(ComoditiesName.Text.Trim()))//商品名称
        {
            search += "&comodName=" + Common.FormatParameter(ComoditiesName.Text).Trim();
        }
        if (!string.IsNullOrEmpty(TypeName.Text))//类型
        {
            search += "&TypeName=" + Common.FormatParameter(TypeName.Text.Trim());
        }
        if (!string.IsNullOrEmpty(brand.Text))//品牌
        {
            search += "&brand=" + Common.FormatParameter(brand.Text.Trim());
        }
        if (!string.IsNullOrEmpty(ddltypeSale.SelectedValue))//销售类型
        {
            search += "&typeSale=" + Common.FormatParameter(ddltypeSale.SelectedValue.Trim());
        }

        if (!string.IsNullOrEmpty(ddrDepartment.SelectedValue))//部门
        {
            search += "&deptid=" + Common.FormatParameter(ddrDepartment.SelectedValue.Trim());
        }

        PageNavigator1.Url = "../Finance/ProfitClear.aspx?moduid=" + hfxs.Value + search;
        Response.Redirect("ProfitClear.aspx?moduid=" + hfxs.Value + search);
    }


    protected void GvData_RowDataBound(object sender, GridViewRowEventArgs e)//在邦定数据
    {
        //f.checkLevels(Request.Cookies["user"].Values["roleid"], hfxs.Value, 4, GvDataType, btndel, btnallflag, btnAdd);//权限
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int typeSale = Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "typeSale"));
            if (typeSale == 1)
            {
                e.Row.Cells[14].Text = "零售";
            }
            else if (typeSale == 2)
            {
                e.Row.Cells[14].Text = "批发";
            }
            else if (typeSale == 3)
            {
                e.Row.Cells[14].Text = "工程";
            }
            else
            {
                e.Row.Cells[14].Text = "未知";
            }
        }
    }


    private void initKdate()
    {
        txtJdate.Text = DateTime.Now.Date.ToString("yyyy-MM-dd");//当前日期
        txtKdate.Text = DateTime.Now.Date.ToString("yyyy-MM") + "-01";//当月的第一天
    }
    protected void Excel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=SaleClear" + DateTime.Now.Date.ToString("yyyyMMdd") + ".xls");
        // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码！！！
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        //  turn off paging 

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        this.GvData.RenderControl(htw);
        string strHtml = sw.ToString().Trim();
        Response.Output.Write(strHtml);
        Response.Flush();
        Response.End();
        // turn the paging on again 

    }
    //添加一个空方法,防止   GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内错误
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm. control is rendered for
    }
}
